<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class RedisController extends Controller
{
    public $user_number = 50; // 允许进入队列的人数

    /**
     * 这个方法，相当于点击进入商品详情页,开启秒杀活动
     */
    public function index()
    {
        $res = DB::table('goods')->where(['is_delete' => 0])->get();
        if (!empty($res)) {
            //1、删除旧redis队列
            foreach ($res as $k => $v) {
                //商品id
                $goods_id = $v->goods_id;
                Redis::command('del', ['acst_goods_high_lines' . $goods_id]);
            }
            //2、准点插入记录到redis
            foreach ($res as $k => $v) {
                //商品id
                $goods_id = $v->goods_id;
                //库存数量
                $num = $v->deduct_stock_type;
                //json转换
                $in_list = json_encode([
                    'goods_id'=>$v->goods_id,
                    'goods_name'=>$v->goods_name
                ]);
                for ($i = 0; $i < $num; $i++) {
                    Redis::lpush('acst_goods_high_lines' . $goods_id, $in_list);
                    $r= Redis::lrange('acst_goods_high_lines' . $goods_id, 0, 10);
                    var_dump($r);
                }
            }

        }
    }

    public function buy(Request $request)
    {
        $goods_id = $request->input('goods_id');
        //获取队列长度
        $leng = Redis::lLen('acst_goods_high_lines' . $goods_id);
        if ($leng > 0) {
            //移除一条记录
            Redis::lpop('acst_goods_high_lines' . $goods_id);
            //减去库存---增加成功开团数
            $sql = 'update goods set deduct_stock_type = deduct_stock_type-1,sales_actual=sales_actual+1  where goods_id = ' . $goods_id . ' limit 1';
            DB::select($sql);
            $this->result($goods_id);

        } else {
            return view('over');
        }

    }
    /**
     * 查看抢到结果
     */
    public function result($goods_id)
    {
        $result = Redis::lrange('acst_goods_high_lines'.$goods_id, 0, 20);
        dd($result);
    }
}
